## main.py
from flask import Flask, render_template, jsonify, request
from apscheduler.schedulers.background import BackgroundScheduler
import logging
from config import ConfigLoader
from scheduler import Scheduler

# Initialize Flask app
app = Flask(__name__, template_folder='templates', static_folder='static')

# Configure logging to include timestamp
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')

@app.route('/')
def index():
    """Serve the index HTML page."""
    return render_template('index.html')

@app.route('/api/fetch_and_send', methods=['POST'])
def fetch_and_send():
    """API endpoint to manually trigger fetch and send operation."""
    try:
        keywords = request.json.get('keywords', [])
        if not keywords:
            raise ValueError('Keywords are required for fetching and sending.')
        
        scheduler = Scheduler()
        # Schedule fetching immediately with provided keywords
        scheduler.schedule_fetching_now(keywords)
        return jsonify({'message': 'Fetching and sending process initiated'}), 200
    except ValueError as ve:
        logging.warning(f"Validation error: {ve}")
        return jsonify({'error': str(ve)}), 400
    except Exception as e:
        logging.error(f"Failed to initiate fetch and send process: {e}")
        return jsonify({'error': 'Internal server error'}), 500

def setup_scheduler():
    """Set up APScheduler to fetch abstracts and send them at regular intervals."""
    try:
        config = ConfigLoader.load_config()
        scheduler = BackgroundScheduler()
        scheduler.add_job(
            func=Scheduler().schedule_fetching,
            trigger='interval',
            hours=config.get('fetch_interval_hours', 24),
            id='scheduled_fetching',
            replace_existing=True)
        scheduler.start()
    except Exception as e:
        logging.error(f"Error setting up scheduler: {e}")

if __name__ == '__main__':
    setup_scheduler()
    app.run(debug=False, port=5000)  # Turn off debug in production-like environments
